package com.qf.service.impl.blog;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.api.blog.entity.SiteInfoEntity;
import com.qf.api.blog.service.ArticleService;
import com.qf.api.blog.service.CategoryService;
import com.qf.api.blog.service.SiteInfoService;
import com.qf.api.blog.service.TagService;
import com.qf.api.front.vo.WebsiteInfoVO;
import com.qf.core.constant.RedisConstant;
import com.qf.dao.blog.mapper.SiteInfoMapper;
import com.qf.redis.utils.RedisUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
* @author sin
* @description 针对表【t_site_info(博客配置信息表)】的数据库操作Service实现
* @createDate 2025-05-23 14:19:29
*/
@Service
@Slf4j
public class SiteInfoServiceImpl extends ServiceImpl<SiteInfoMapper, SiteInfoEntity>
    implements SiteInfoService {

    @Autowired
    private TagService tagService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CategoryService categoryService;

    @Resource
    private RedisUtils redisUtils;

    private static final Long SITE_ID = 1L;

    @Override
    public WebsiteInfoVO getWebSiteInfo() {
        SiteInfoEntity siteInfo = this.getById(SITE_ID);
        WebsiteInfoVO websiteInfoVO = BeanUtil.copyProperties(siteInfo, WebsiteInfoVO.class);
        // 获取标签数
        long tagCount = tagService.count();
        // 获取分类数
        long categoryCount = categoryService.count();
        // 获取文字数
        long articleCount = articleService.count();
        // 获取总字数
        long wordCount = articleService.getWordCount();

        websiteInfoVO.setArticleCount(articleCount);
        websiteInfoVO.setCategoryCount(categoryCount);
        websiteInfoVO.setTagCount(tagCount);
        websiteInfoVO.setWordCount(wordCount);
        return websiteInfoVO;
    }

    @Override
    public void addVisitorTime(String ip) {
        boolean res = redisUtils.setIfAbsent(RedisConstant.VISITOR_BLOG_IP + ip,"1",24, TimeUnit.HOURS);
        if(res) {
            // MySQL 同步
            UpdateWrapper<SiteInfoEntity> wrapper = new UpdateWrapper<>();
            wrapper.setSql("visit_count = visit_count + 1");
            wrapper.eq("id", SITE_ID);
            this.update(wrapper);
        }
    }
}




